package com.sprucetec.live.config;

import com.sprucetec.hawkeye.metric.web.MetricInterceptor;
import com.sprucetec.hawkeye.sdk.HawkeyeEngine;
import com.sprucetec.hawkeye.trace.web.TraceInterceptor;
import com.sprucetec.live.interceptor.LoginInterceptor;
import com.sprucetec.live.interceptor.RestInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;
import javax.annotation.PostConstruct;

/**
 * 拦截器配置类
 *
 * @author lixiaodong
 */
@Configuration
public class WebInterceptorConfig extends WebMvcConfigurationSupport {
    private static HawkeyeEngine hawkeyeEngine;

    protected boolean isInitialized = false;

    /**
     * 初始化鹰眼bean
     */
    @PostConstruct
    protected void initialize() {
        if (!isInitialized) {
            synchronized (this) {
                if (isInitialized)
                    return;

                try {
                    Class<?> clazz = Class.forName("com.sprucetec.hawkeye.sdk.HawkeyeEngine");
                    hawkeyeEngine = (HawkeyeEngine) clazz.newInstance();
                    hawkeyeEngine.start();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                isInitialized = true;
            }
        }
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {


        registry.addInterceptor(new RestInterceptor()).addPathPatterns("/rest/**");
        //权限认证拦截器
        registry.addInterceptor(loginInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/static/**", "/rest/**", "/common/**", "/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**");

        super.addInterceptors(registry);
    }

    @Override
    //需要告知系统，这是要被当成静态文件的！
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 设置文件上传的文件不拦截
//	        registry.addResourceHandler("/upload/**").addResourceLocations("file:"+ TaleUtils.getUplodFilePath()+"upload/");
        //第一个方法设置访问路径前缀，第二个方法设置资源路径
        registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");

    }


    @Bean
    public LoginInterceptor loginInterceptor() {
        return new LoginInterceptor();
    }

    @Bean
    public TraceInterceptor traceInterceptor() {
        return new TraceInterceptor();
    }

    @Bean
    public MetricInterceptor metricInterceptor() {
        return new MetricInterceptor();
    }


}
